package com.demo.sensor;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

import com.example.myalldemo.R;

public class SensorGravity extends Activity implements SensorEventListener {

	private TextView tv;
	private SensorManager sm;
	private Sensor sensor_acce;
	private float[] gravity;
	private float[] motion;
	private double ratio;
	private double mAngel;
	private int counter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sensorgravity);
		tv = (TextView) findViewById(R.id.text);
		sm = (SensorManager) getSystemService(SENSOR_SERVICE);
		sensor_acce = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		counter = 0;
		gravity = new float[3];
		motion = new float[3];
	}

	@Override
	protected void onPause() {
		super.onPause();
		sm.unregisterListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		sm.registerListener(this, sensor_acce,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		for (int i = 0; i < 3; i++) {
			gravity[i] = (float) (0.1 * event.values[i] + 0.9 * gravity[i]);
			motion[i] = event.values[i] - gravity[i];
		}
		ratio = gravity[1] / SensorManager.GRAVITY_EARTH;
		ratio = ratio > 1.0 || ratio < -1.0 ? 1.0 : ratio;

		mAngel = Math.toDegrees(Math.acos(ratio));
		mAngel = gravity[2] < 0 ? -mAngel : mAngel;

		if (counter++ % 10 == 0) {
			String msg = String
					.format("Raw values\nX: %8.4f\nY: %8.4f\nZ: %8.4f\n"
							+ "Gravity\nX: %8.4f\nY: %8.4f\nZ: %8.4f\n"
							+ "Motion\nX: %8.4f\nY: %8.4f\nZ: %8.4f\nAngel: %8.1f",
							event.values[0], event.values[1], event.values[2],
							gravity[0], gravity[1], gravity[2], motion[0],
							motion[1], motion[2], mAngel);
			tv.setText(msg);
			counter = 1;
		}

	}
}
